package cn.wolfcode.shop.cloud.filter;

import cn.wolfcode.shop.cloud.Result;
import cn.wolfcode.shop.cloud.util.CookieUtil;
import cn.wolfcode.shop.cloud.web.feign.MemFeignApi;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CookieRefreshFilter extends ZuulFilter {

    @Autowired
    private MemFeignApi memFeignApi;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }


    @Override
    public boolean shouldFilter() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String token = CookieUtil.getCookie(request, "token");
        if (!StringUtils.isEmpty(token)) {   //客户端是否有token
            return true;
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {

        //延长redis的过期时间
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        HttpServletResponse response = requestContext.getResponse();

        String token = CookieUtil.getCookie(request,"token");
        Result<Boolean> result = memFeignApi.refreshTime(token);
        //延长cookie的过期时间
        if(result.getCode() == 200 && result.getData()){
            CookieUtil.addCookie("token",token,1800,response);
        }
        //requestContext.setSendZuulResponse(false); //登录鉴权的filter 不过别的也不需要过了
        return null;
    }
}
